package com.sxz.sbs.applibrary.dialog.input;

import android.app.Dialog;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.sxz.sbs.applibrary.R;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 值类型 键盘弹框
 */

public class ValueInputBoardDialog extends Dialog {
    private Context context;
    /**
     * 初始值
     */
    private String initialValue = "";
    /**
     * 需要截取的长度
     */
    private int subLength;
    private UnitEnum unit;
    private RecyclerView mRecyclerView;
    private RelativeLayout mClose;
    private TextView sure,board_hint_tv;
    private EditText etContent;
    private KeyBoardAdapter adapter;
    private OnDialogResultListener onDialogResultListener;
    /**
     * 键盘数据源
     */
    private ArrayList<Map<String, String>> valueList = new ArrayList<>();
    private int MAX_LENGTH  =   12;

    public ValueInputBoardDialog(@NonNull Context context, @NonNull String value, UnitEnum type) {
        super(context, R.style.Input_board_dialog_theme);
        this.context = context;
        this.initialValue = value;
        this.unit = type;
        this.subLength = type.getValue().length();
        setContentView(R.layout.value_input_board_layout);
        setKeyBoardData();
        initDialog();
        initView();
        initListener();
    }

    public void setOnDialogResultListener(OnDialogResultListener onDialogResultListener) {
        this.onDialogResultListener = onDialogResultListener;
    }

    /**
     * 设置键盘数据
     */
    private void setKeyBoardData() {
        for (int i = 1; i < 13; i++) {
            Map<String, String> map = new HashMap<>();
            if (i < 10) {
                map.put("name", String.valueOf(i));
            } else if (i == 10) {
                if (unit == UnitEnum.AREA) {
                    map.put("name", ".");
                } else {
                    map.put("name", "");
                }
            } else if (i == 11) {
                map.put("name", String.valueOf(0));
            } else if (i == 12) {
                map.put("name", "");
            }
            valueList.add(map);
        }
    }

    /**
     * 初始化控件
     */
    private void initView() {
        mRecyclerView = (RecyclerView) findViewById(R.id.key_board_rv);
        mRecyclerView.setLayoutManager(new GridLayoutManager(context,3));
        mRecyclerView.addItemDecoration(new DividerGridItemDecoration(context,1,R.color.gray));
        mClose = (RelativeLayout) findViewById(R.id.key_board_close);
        sure = (TextView) findViewById(R.id.key_board_sure);
        etContent = (EditText) findViewById(R.id.et_board_value);
        board_hint_tv = (TextView) findViewById(R.id.board_hint_tv);
        adapter = new KeyBoardAdapter(context,valueList);
        mRecyclerView.setAdapter(adapter);
        if (unit == UnitEnum.AREA) {
            board_hint_tv.setText("请输入面积");
        } else if (unit == UnitEnum.YEAR) {
            board_hint_tv.setText("请输入使用年限");
        }
        forbidKeyBoard();
        configFocusable();
        if (initialValue.length() > 0) {
            etContent.setText(initialValue + unit.getValue());
            etContent.setSelection(etContent.getText().toString().length()-subLength);
        }
    }

    /**
     * 监听事件
     */
    private void initListener() {
        /**
         * 列表点击事件
         */
        adapter.setOnItemClickListener(new KeyBoardAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                // 首次不能为0
                if (etContent.getText().toString().length() <= 0 && (position == 10 || position == 9)) {
                    return;
                }
                if (etContent.getText().toString().length() >= MAX_LENGTH-1) {
                    return;
                }
                if (position != 11) {
                    if (etContent.getText().toString().length() > 0) {
                        etContent.setText(
                                etContent.getText().toString().
                                        substring(0,etContent.getText().toString().length()-subLength)+valueList.get(position).get("name")
                                        + unit.getValue());
                    } else {
                        etContent.setText(valueList.get(position).get("name") + unit.getValue());
                    }
                    etContent.setSelection(etContent.getText().toString().length() - subLength);
                } else if (position == 11) {
                    dismiss();
                }
            }
        });
        /**
         * 点击删除键
         */
        mClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(getContent())) {
                    setValue();
                    if (etContent.getText().toString().length() == subLength) {
                        etContent.setText("");
                    }
                }
            }
        });
        /**
         * 点击确定键
         */
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String newContent;
                if (onDialogResultListener != null) {
                    if (!TextUtils.isEmpty(getContent())) {
                        newContent = getContent().substring(0, getContent().length()-unit.getValue().length());
                        if (newContent.endsWith(".")) {
                            newContent = newContent.replace(".","");
                        }
                        onDialogResultListener.onResult(newContent, unit.getValue());
                    } else {
                        newContent = getContent();
                        onDialogResultListener.onResult(newContent,"");
                    }
                    }
                dismiss();
            }
        });
        /**
         * 长按删除  清空
         */
        mClose.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                etContent.setText("");
                return true;
            }
        });
        /**
         * 禁止光标移动
         */
        etContent.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_UP:
                        //禁止光标移动
                        if (etContent.getText().toString().length() >0) {
                            etContent.setSelection(etContent.getText().toString().length() - subLength);
                        }
                        break;
                    default:
                        break;
                }
                return true;
            }
        });
    }
    /**
     * 禁止键盘弹出
     */
    private void forbidKeyBoard() {
        this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        try {
            Class<EditText> cls = EditText.class;
            Method setSoftInputShownOnFocus;
            setSoftInputShownOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
            setSoftInputShownOnFocus.setAccessible(true);
            setSoftInputShownOnFocus.invoke(etContent, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化光标
     */
    private void configFocusable() {
        etContent.setFocusable(true);
        etContent.setFocusableInTouchMode(true);
        etContent.requestFocus();//获取焦点 光标出现
    }

    /**
     * 配置dialog
     */
    private void initDialog() {
        this.setCanceledOnTouchOutside(true);
        this.setCancelable(true);
        Window window = this.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(R.style.bottom_dialog_anim);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        window.setAttributes(lp);
    }
    /**
     * 单位枚举
     */
    public enum  UnitEnum {
       AREA("㎡"),
       RENT("元/月"),
       SELL("元"),
       YEAR("年");
       private String value;

        UnitEnum(String value) {
            this.value = value;
        }
        public String getValue() {
            return value;
        }
    }
    /**
     * 结果监听回调
     */
    public interface OnDialogResultListener {
        /**
         *  输入结果返回
         * @param value 输入的值
         * @param unit 单位
         */
        void onResult(String value, String unit);
    }

    /**
     * 获取输入内容
     * @return
     */
    private String getContent () {
        return etContent.getText().toString();
    }
    public void setValue () {
        etContent.setText(etContent.getText().toString().substring(0, etContent.getText().toString().length() - (unit.getValue().length() +1) ) +unit.getValue());
        etContent.setSelection(etContent.getText().toString().length() - subLength);
    }
}
